package com.wing.util;

import cn.hutool.core.util.StrUtil;
import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * Https工具类
 *
 * @author xiayang
 */
public class HttpsUtils {

    /**
     * post请求-json
     *
     * @param url        请求url
     * @param headers    请求头参数
     * @param paramsJson json参数
     * @return
     * @throws Exception
     */
    public static String httpsPostByJson(String url, Map<String, String> headers, String paramsJson) {
        // 构建请求参数
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            trustAllHosts();
            URL url2 = new URL(url);
            HttpsURLConnection urlCon = (HttpsURLConnection) url2.openConnection();
            urlCon.setHostnameVerifier(DO_NOT_VERIFY);
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setRequestMethod("POST");
            // 设置通用的请求属性
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    urlCon.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            urlCon.setRequestProperty("Content-type", "application/json;charset=UTF-8");
            urlCon.setConnectTimeout(15 * 1000);// 设置超时时间
            urlCon.setReadTimeout(15 * 1000);
            // 发送POST请求必须设置如下两行
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStream os = urlCon.getOutputStream();
            // 参数是键值队 , 不以"?"开始
            if (StrUtil.isNotEmpty(paramsJson)) {
                os.write(paramsJson.getBytes());
            }
            os.flush();
            // 发送请求参数
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    public static String httpsGet(String url) {
        // 创建SSLContext对象，并指定使用TLS协议
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            // 创建URL对象
            URL url1 = new URL(url);
            // 创建HttpsURLConnection对象
            HttpsURLConnection connection = (HttpsURLConnection) url1.openConnection();
            connection.setSSLSocketFactory(sslSocketFactory);
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            // 发送请求
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // 读取响应数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            // 输出响应数据
            return response.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    private static void trustAllHosts() {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String url = "https://openapi.chanjet.com/auth/appTicket/resend";
        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", "HARlwiwZ");
        headers.put("appSecret", "6917C22E277D00702475C3C089577206");

        String result = httpsPostByJson(url, headers, null);
        System.out.println("返回结果：" + result);
    }
}
